package com.feimaopian.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class JwtUtils {
    public static final long EXPIRE = 1000 * 60 * 60 * 24*7;  //过期时间7天
    public static final String SECRET = "FeiMaoPian";//设置密钥

    public static String create(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((K, V) -> {
            builder.withClaim(K, V);     //遍历map将用户数据放入负载中
        });
        Date now = new Date();
        Date expires = new Date(now.getTime() + EXPIRE);
        builder.withIssuedAt(now);  //设置创建时间
        builder.withExpiresAt(expires);     //设置过期时间
        String uuid = UUID.randomUUID().toString().replaceAll("-","");	//通过UUID生成一个唯一标识
        builder.withJWTId(uuid);    //设置唯一标识
        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    public static boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);  // 如果验证通过，则不会把报错，否则会报错
            return true;
        } catch (TokenExpiredException e) {//令牌过期异常
            return false;
        } catch (SignatureVerificationException e) {//签名不一致异常
            return false;
        } catch (AlgorithmMismatchException e) {//算法不匹配异常
            return false;
        } catch (InvalidClaimException e){//失效的payload异常
            return false;
        }catch (Exception e) {
            return false;
        }
    }


    public static DecodedJWT getToken(String token) {
        //解析传来的字符串
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}

